#include "server.h"
#include <QMessageBox>
#include "loger.h"
Server::Server(QObject *parent) : QObject(parent)
{
    connections = new QMap<QString, Connection *>();
}
Server::~Server(){
    QString info("服务器Server已析构");
    Loger::info(info);
}
/**
 * 启动服务器
 * @brief start
 * @param config 配置为空则采用默认配置
 */
bool Server::start(ServerConfig * config ){
    if(httpParser == nullptr){
        httpParser = new HttpParser(this);
    }
    if(config == nullptr){
        this->config =  new ServerConfig(this);
    }
    if(connector == nullptr){
        connector = new Connector(this->config->getPort(),this);
        //事件绑定
        connect(connector, SIGNAL(newConnection(Connection*)), this, SLOT(newConnection(Connection*)));
    }
    bool result = connector->startListen();
    if(result){
        //启动监听成功
        QMessageBox::about(nullptr, "提示", "启动成功");
        QString info("启动服务器成功,端口:");
        info.append(QString::number(this->config->getPort()));
        Loger::info(info);
    }else{
        QMessageBox::warning(nullptr, "警告", "启动失败");
    }
    return result;
}
/**
 * 停止服务器
 * @brief stop
 */
void Server::stop(){
    connector->close();
    QString info("服务已关闭");
    Loger::info(info);
}
/**
 * 新的连接到达
 * @brief newConnection
 * @param conn
 */
void Server::newConnection(Connection * conn){
    QString key = createMapKey(conn);
    //放入到集合中
    connections->insert(key, conn);
    connect(conn, SIGNAL(recvdData(Connection *)), this, SLOT(slotReadClientData(Connection *)));
    connect(conn, SIGNAL(disconnected(Connection *)), this, SLOT(slotClientDisconnected(Connection *)));
    QString info("新的连接到达:");
    info.append(key);
    info.append(" 当前连接数:");
    info.append(QString::number(connections->size()));
    Loger::info(info);

}
/**
 * 有数据可读
 * @brief slotReadClientData
 */
void Server::slotReadClientData(Connection *conn){
    QString info("接收到数据:");
    //info.append(QString(conn->readAll()));
    Loger::info(info);
    //响应头信息
//           QString s = "HTTP/1.0 200\r\n"
//                      "Server: wz simple httpd 1.0\r\n"
//                      "Content-Length: 20\r\n"
//                      "Content-Type: json\r\n"
//                      "\r\n";
//           //响应体
//           s.append("{\"name\":\"denglibin\"}");
    httpParser->service(conn);
}
/**
 * 连接断开
 * @brief slotClientDisconnected
 */
void Server::slotClientDisconnected(Connection *conn){
    QString key = createMapKey(conn);
    conn->close();
    connections->remove(key);
    conn->deleteLater(); //析构
    QString info(key);
    info.append(QString(" 已断开"));
    info.append(" 当前连接数:");
    info.append(QString::number(connections->size()));
    Loger::info(info);
}
QString Server::createMapKey(Connection *conn){
    QString s = conn->peerAddress().toString()+"_";
    s.append(QString::number(conn->peerPort(), 10));
    return s;
}
